package com.ruoyi.test.dao;

import com.ruoyi.test.domain.Channel;
import com.ruoyi.test.dto.JoinChannelDto;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ChannelDao {
    @Select("select name, description from chat_channel WHERE is_deleted = 0")
    List<Channel> getAllChannel();

    @Select("select name, description from chat_channel WHERE is_deleted = 1")
    List<Channel> getAllDeletedChannel();

    @Update("update chat_channel set description=#{description}, is_deleted = 0 where name=#{name}")
    void addForUpdate(Channel channel);

    @Insert("insert into chat_channel (name, description) values(#{name}, #{description})")
    void add(Channel channel);

    // 根据频道名称查找加入了某一个频道的所有用户
    @Select("select cu.nickname\n" +
            "FROM chat_user cu\n" +
            "JOIN chat_user_channel cuc ON cu.id = cuc.user_id\n" +
            "JOIN chat_channel cc ON cuc.channel_id = cc.id\n" +
            "WHERE cc.name = #{channelName} AND cuc.is_deleted = 0 AND cc.is_deleted=0;")
    List<String> getAllUserByChannelName(String channelName);

    // -------------------- 某一个用户加入某一个频道 -----------------------------

    // 查找数据库中的行，表示用户表与频道表有关
    @Select("SELECT cuc.user_id \n" +
            "FROM chat_user_channel cuc\n" +
            "JOIN chat_user cu ON cuc.user_id = cu.id\n" +
            "JOIN chat_channel cc ON cuc.channel_id = cc.id\n" +
            "WHERE cu.nickname = #{nickname} AND cc.name = #{channelName};\n")
    List<Long> getUserAndChannel(JoinChannelDto joinChannelDto);

    @Update("UPDATE chat_user_channel cuc\n" +
            "JOIN chat_user cu ON cuc.user_id = cu.id\n" +
            "JOIN chat_channel cc ON cuc.channel_id = cc.id\n" +
            "SET cuc.is_deleted = 0\n" +
            "WHERE cu.nickname = #{nickname} AND cc.name = #{channelName};\n")
    void joinChannelForUpdate(JoinChannelDto joinChannelDto);

    @Insert("INSERT INTO chat_user_channel (user_id, channel_id, is_deleted)\n" +
            "SELECT cu.id, cc.id, 0\n" +
            "FROM chat_user cu, chat_channel cc\n" +
            "WHERE cu.nickname = #{nickname} AND cc.name = #{channelName}\n")
    void joinChannelForInsert(JoinChannelDto joinChannelDto);

    // -------------------- 某一个用户加入某一个频道结束 -----------------------------

    @Update("UPDATE chat_user_channel cuc\n" +
            "JOIN chat_user cu ON cuc.user_id = cu.id\n" +
            "JOIN chat_channel cc ON cuc.channel_id = cc.id\n" +
            "SET cuc.is_deleted = 1\n" +
            "WHERE cu.nickname = #{nickname}  AND cc.name = #{channelName} ;")
    void exitChannel(JoinChannelDto joinChannelDto);

    @Update("UPDATE chat_channel\n" +
            "SET is_deleted = 1\n" +
            "WHERE name = #{channelName} ;")
    void removeChannel(String channelName);
}
